package im.vinci.server.discovery.persistence;

import im.vinci.server.discovery.domain.Music;
import im.vinci.server.discovery.domain.wrappers.DiscoveryResponse;
import im.vinci.server.discovery.service.MusicDataFile;
import im.vinci.server.utils.JsonUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;

import javax.annotation.PostConstruct;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by mingjie on 16/12/10.
 */
@Repository
public class DiscoveryMapper {

    private static final String DATA_FILE = "src/main/resources/DiscoveryData.json";

    private Logger logger = LoggerFactory.getLogger(getClass());

    private DiscoveryResponse response;

    private Map<Long, List<Music>> map;

    @PostConstruct
    public void init() {
        try {
            logger.info("Read DiscoveryData");

            buildCache();
        } catch (Exception e) {
            logger.error("Read DiscoveryData error", e);
        }
    }

    private MusicDataFile readFile(String fileName) throws Exception {
        return JsonUtils.getHttpObjectMapperInstance().readValue(new File(fileName), MusicDataFile.class);
    }

    private void buildCache() throws Exception {
        MusicDataFile dataFile = readFile(DATA_FILE);
        DiscoveryResponse tempResponse = new DiscoveryResponse();
        tempResponse.setCategories(dataFile.getCategories());
        tempResponse.setChannels(dataFile.getChannels());

        HashMap<Long, List<Music>> tempMap = new HashMap<Long, List<Music>>();

        HashMap<Long, Music> musicMap = dataFile.getMusicMap();
        HashMap<Long, List<Long>> musicListMap = dataFile.getMusicListMap();

        for (Map.Entry<Long, List<Long>> entry : musicListMap.entrySet()) {
            List<Music> musicList = new ArrayList<Music>();
            for (Long songId : entry.getValue()) {
                Music music = musicMap.get(songId);
                musicList.add(music);
            }
            tempMap.put(entry.getKey(), musicList);
        }

        response = tempResponse;
        map = tempMap;
    }

    public DiscoveryResponse showHomePage() {
        return response;
    }

    public List<Music> getMusicList(long id) {
        return map.get(id);
    }
}
